package com.WaVel.controller.admin;

import com.Emplyment.dto.StudyMaterialDto;
import com.Emplyment.result.Result;
import com.Emplyment.vo.StudyMaterialsVo;
import com.WaVel.service.StudyMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/studymaterial")
@Slf4j
public class StudyMaterialController {

    @Autowired
    private StudyMaterialService studyMaterialService;

    @GetMapping("/getstudymaterial")
    public Result<List<StudyMaterialDto>> getStudyMaterial() {
        List<StudyMaterialDto> studyMaterial = studyMaterialService.getStudyMaterial();
        log.info("接收到的数据为：{}: ",studyMaterial);
        return Result.success(studyMaterial);
    }

    @PostMapping("/addstudymaterial")
    public Result addStudyMaterial(@RequestParam MultipartFile file, @RequestParam String fileName) {
        studyMaterialService.addStudyMaterial(file, fileName);
        return Result.success();
    }

    @DeleteMapping("/deletestudymaterial")
    public Result deleteStudyMaterial(@RequestParam Integer id) {
        studyMaterialService.deleteStudyMaterial(id);
        return Result.success();
    }

    @GetMapping("/preview/{id}")
    public ResponseEntity<Resource> preview(@PathVariable Integer id) throws IOException {
        StudyMaterialsVo studyMaterialsVo = studyMaterialService.getStudyMaterialById(id);

        byte[] file = studyMaterialsVo.getFile();
        Resource resource = new ByteArrayResource(file);
        String fileName = studyMaterialsVo.getFileName();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
    }


}
